package concept.misc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * Handy quick code for reading data in text files for testing
 * 
 * @author gawain.hammond
 * 
 */
public class FileParser
{

	/**
	 * Parse a text fieland return the data in a List object
	 * 
	 * @param file
	 * @return - The text file data, one element per line
	 */
	public static List<String> getTextFileAsList(String file)
	{

		List<String> output = new ArrayList<String>();

		try
		{
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			String line = "";
			while ((line = br.readLine()) != null)
			{
				if (!line.startsWith("#"))
				{
					output.add(line.trim() + " ");
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new RuntimeException(e);
		}

		return output;
	}

	/**
	 * 
	 * Parse a text file and return the entire contents as a string
	 * 
	 * @param filename
	 * @return
	 */
	public static String getTextFileAsString(String filename)
	{

		String fileText = "";
		List<String> fileLines = getTextFileAsList(filename);
		for (String line : fileLines)
		{
			fileText += line;
		}
		return fileText;

	}

	/**
	 * Return the contents of a text file as a map of key value pairs. the text
	 * file must contain line that conform to the this format:
	 * 
	 * Key1=Value1 Key2=Value2 ...
	 * 
	 * @param filename
	 * @return
	 */
	public static Map<String, String> getTextFileAsMap(String filename)
	{
		Map<String, String> map = new HashMap<String, String>();
		List<String> fileLines = getTextFileAsList(filename);
		for (String line : fileLines)
		{
			String key = line.split("=")[0];
			String value = (line.split("=")[1]).trim();
			map.put(key, value);
		}
		return map;
	}

	/**
	 * Return the csv data from a csv file as the grish special: List<Map<String,
	 * String>>
	 * 
	 * @param filename
	 * @return The grish favourite, a Map in a List
	 */
	public static List<Map<String, String>> getCsvFileAsMap(String filename)
	{
		final String CSV_COMMA_DELIMITER = ",";

		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		List<String> fileLines = getTextFileAsList(filename);

		String[] columns = fileLines.get(0).split(CSV_COMMA_DELIMITER);
		for (int lineCounter = 1; lineCounter < fileLines.size(); lineCounter++)
		{
			Map<String, String> map = new HashMap<String, String>();
			String[] line = fileLines.get(lineCounter).split(CSV_COMMA_DELIMITER);
			for (int colCounter = 0; colCounter < columns.length; colCounter++)
			{
				String columnKey = columns[colCounter];
				String value = line[colCounter];
				map.put(columnKey, value);
			}
			list.add(map);
		}
		return list;
	}

	/**
	 * Returns a List of columns names if a single text file holds a single
	 * record. The data in this text file must contain the data in Key/Value
	 * pairs, like below:
	 * 
	 * Key1=Value1 Key2=Value2
	 * 
	 * This method will return a List containing the String values:
	 * 
	 * {"Key1", "Key2"}
	 * 
	 * @param file
	 * @return
	 */
	public static List<String> getBatchIdHeaderFields(String file)
	{
		List<String> fileText = getTextFileAsList(file);
		List<String> headerFields = new ArrayList<String>();
		for (String line : fileText)
		{
			headerFields.add(line.split("=")[0]);
		}

		return headerFields;
	}

	/**
	 * 
	 * Converts an {@link InputStream} object in to a {@link String}
	 * 
	 * @param is
	 * @return
	 */
	public static String convertStreamToString(InputStream is)
	{
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try
		{
			while ((line = reader.readLine()) != null)
			{
				sb.append(line + "\n");
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				is.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}

		return sb.toString();
	}

	/**
	 * A main method for cheap testing of methods in this class
	 */
	public static void main(String[] args) throws Exception
	{
		File file = new File("C:\\java_workspace\\BatchID_Processor\\1");
		deleteFiles(file);
	}
	private static void deleteFiles(File dir)
	{
		for(File f:dir.listFiles())
		{
			if(f.list().length>0)
			{
				deleteFiles(f);
			}
			else
			{
				f.delete();
			}
		}
	}

}
